package com.zy.面向对象.伴生对象

object Test {

  // 伴生对象其他内容见com.zy.基础.伴生对象
  def main(args: Array[String]): Unit = {

    // 调用了类的静态方法构造器
    val student1 = Student.newInstance("张三", 12)
    println(student1.toString)
    // 调用了类的静态方法构造器
    val student2 = Student.apply("李四", 13)
    println(student2.toString)
    // 如果类的静态方法构造器为apply，则可以省略.apply()
    val student3 = Student("王五", 17)
    println(student3.toString)

  }

}

// 私有类的构造方法，使用单例对象的静态方法创建
class Student private(var name: String, var age: Int){

  override def toString = s"Student($name, $age)"
}

object Student {

  def newInstance(name: String, age: Int): Student = new Student(name, age)

  def apply(name: String, age: Int): Student = new Student(name, age)
}